<script setup lang="ts">
import type { ProjectInfoDetail } from '@/api/types/finance'
import type { AttachmentItem } from '@/components/AttachmentList.vue'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getProjectFileList, getProjectInfoDetailById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import AttachmentList from '@/components/AttachmentList.vue'
import DetailCard from '@/components/DetailCard.vue'
import { getStatusName } from '@/constants/enums'
import { useFlow } from '@/hooks/useFlow'

// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '项目详情',
  },
})

// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<ProjectInfoDetail | null>(null)
const errorMessage = ref('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')
const projectFiles = ref<AttachmentItem[]>([])
const filesLoading = ref(false)
const filesErrorMessage = ref('')

// 获取业务详情数据
async function getBusinessData() {
  loading.value = true
  errorMessage.value = ''
  try {
    // 先获取流程实例
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }

    // 使用流程实例中的业务key获取业务详情
    if (currentProcess.value && currentProcess.value.businessKey) {
      const res = await getProjectInfoDetailById(currentProcess.value.businessKey)
      businessData.value = res.data || null
      console.log('获取项目详情成功:', res)

      // 获取项目文件列表
      if (res.data?.id) {
        await fetchProjectFiles(res.data.id)
      }
    }
    else {
      throw new Error('无法获取业务key')
    }
  }
  catch (error) {
    errorMessage.value = '获取数据失败，请重试'
    console.error('获取项目详情失败:', error)
  }
  finally {
    loading.value = false
  }
}

// 处理文件预览
function handleFilePreview(item: AttachmentItem, index: number) {
  console.log('预览文件:', item)
  // 使用uni-app的预览API
  if (item.type && ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(item.type)) {
    uni.previewImage({
      current: index,
      urls: projectFiles.value
        .filter(file => ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(file.type))
        .map(file => file.url),
      success: () => {
        console.log('预览图片成功')
      },
      fail: (err) => {
        console.error('预览图片失败:', err)
        uni.showToast({
          title: '预览失败',
          icon: 'none',
        })
      },
    })
  }
  else {
    // 非图片文件尝试使用内置浏览器打开
    uni.openDocument({
      filePath: item.url,
      showMenu: true,
      success: () => {
        console.log('打开文档成功')
      },
      fail: (err) => {
        console.error('打开文档失败:', err)
        uni.showToast({
          title: '无法打开该文件',
          icon: 'none',
        })
      },
    })
  }
}

// 处理文件下载
function handleFileDownload(item: AttachmentItem) {
  console.log('下载文件:', item)
  uni.showLoading({
    title: '下载中...',
  })

  uni.downloadFile({
    url: item.url,
    success: (res) => {
      if (res.statusCode === 200) {
        // 保存文件
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (saveRes) => {
            uni.hideLoading()
            uni.showToast({
              title: '下载成功',
              icon: 'success',
            })
            console.log('文件保存路径:', saveRes.savedFilePath)
          },
          fail: (err) => {
            uni.hideLoading()
            console.error('保存文件失败:', err)
            uni.showToast({
              title: '保存失败',
              icon: 'none',
            })
          },
        })
      }
      else {
        uni.hideLoading()
        uni.showToast({
          title: '下载失败',
          icon: 'none',
        })
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.error('下载文件失败:', err)
      uni.showToast({
        title: '网络错误',
        icon: 'none',
      })
    },
  })
}

// 获取项目文件列表
async function fetchProjectFiles(projectId: string) {
  filesLoading.value = true
  filesErrorMessage.value = ''
  try {
    const files = await getProjectFileList(projectId)
    // 转换为AttachmentItem格式
    projectFiles.value = files.map(file => ({
      id: file.id,
      name: file.fileName,
      url: file.filePath ? file.filePath.replace(/^`|`$/g, '').trim() : '', // 移除首尾的反引号并清理空白
      type: file.fileName.split('.').pop()?.toLowerCase() || 'unknown',
      size: file.fileSize,
      description: file.description || '',
    })).filter(file => file.url) // 过滤掉无效URL
    console.log('获取项目文件列表成功:', projectFiles.value)
  }
  catch (error) {
    filesErrorMessage.value = '获取文件列表失败'
    console.error('获取项目文件列表失败:', error)
  }
  finally {
    filesLoading.value = false
  }
}

// 计算项目基本信息列表
const projectBasicInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '项目名称',
      value: businessData.value.projectName || '--',
    },
    {
      label: '项目编号',
      value: businessData.value.projectNo || '--',
    },
    {
      label: '项目状态',
      value: getStatusName('projectStatus', businessData.value.projectStatus) || businessData.value.projectStatus || '--',
      type: 'status',
    },
    {
      label: '开始日期',
      value: businessData.value.projectStartTime || '--',
      type: 'date',
    },
    {
      label: '结束日期',
      value: businessData.value.projectEndTime || '--',
      type: 'date',
    },
    {
      label: '创建人',
      value: businessData.value.createName || '--',
    },
    {
      label: '创建时间',
      value: businessData.value.createTime || '--',
      type: 'datetime',
    },
  ]
})

// 计算项目财务信息列表
const projectFinanceInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '项目总金额',
      value: businessData.value.projectTotalPrice ?? '0',
      type: 'currency',
    },
    {
      label: '已收金额',
      value: businessData.value.projectReceivedPrice ?? '0',
      type: 'currency',
    },
    {
      label: '应收金额',
      value: businessData.value.projectReceivablePrice ?? '0',
      type: 'currency',
    },
    {
      label: '已付金额',
      value: businessData.value.projectDisbursementPrice ?? '0',
      type: 'currency',
    },
    {
      label: '未付金额',
      value: businessData.value.projectOutstandingPrice ?? '0',
      type: 'currency',
    },
    {
      label: '项目保证金',
      value: businessData.value.projectMargin ?? '0',
      type: 'currency',
    },
    {
      label: '项目押金',
      value: businessData.value.projectDeposit ?? '0',
      type: 'currency',
    },
  ]
})

// 计算项目业务信息列表
const projectBusinessInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '项目核定类型',
      value: getStatusName('projectCompleteType', businessData.value.projectCompleteType) || businessData.value.projectCompleteType || '--',
    },
    {
      label: '项目周期',
      value: `${businessData.value.projectCycle ?? 0}${getStatusName('projectCycle', businessData.value.projectCycleType) || ''}`,
    },
    {
      label: '结算周期',
      value: `${businessData.value.settlementCycle ?? 0}${getStatusName('settlementCycle', businessData.value.settlementCycleType) || ''}`,
    },
    {
      label: '货物品种',
      value: businessData.value.varietyOfGoods || '--',
    },
    {
      label: '货物数量',
      value: businessData.value.quantityOfGoods ?? '--',
    },
    {
      label: '总载重',
      value: businessData.value.totalDeadweight ?? '--',
    },
    {
      label: '备注',
      value: businessData.value.remark || '--',
      forceMultiline: true,
    },
    {
      label: '业务机构',
      value: businessData.value.businessInstitutionName || '--',
    },
    {
      label: '业务部门',
      value: businessData.value.businessDepartmentName || '--',
    },
    {
      label: '业务员',
      value: businessData.value.salesmanName || '--',
    },
  ]
})

// 计算流程信息列表
const processInfo = computed<InfoItem[]>(() => {
  if (!currentProcess.value)
    return []

  return [
    {
      label: '流程实例ID',
      value: currentProcess.value.id || '--',
      forceMultiline: true,
    },
    {
      label: '流程名称',
      value: currentProcess.value.name || '--',
    },
    {
      label: '流程状态',
      value: getStatusName('approvalStatus', currentProcess.value.status) || currentProcess.value.status || '--',
      type: 'status',
    },
    {
      label: '发起人',
      value: currentProcess.value.startUser?.nickname || '--',
    },
    {
      label: '发起时间',
      value: currentProcess.value.startTime || '--',
      type: 'datetime',
    },
  ]
})

// 页面加载时获取数据
onLoad(async (e: any) => {
  console.log('onLoad', e)
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  if (e.id) {
    idValue.value = e.id
    await getBusinessData()
  }
})

// 页面显示时重新获取数据
onShow(async () => {
  if (idValue.value) {
    await getBusinessData()
  }
})
</script>

<template>
  <view class="container bg-slate-50">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <view class="content">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        加载中...
      </view>

      <!-- 错误状态 -->
      <view v-else-if="errorMessage" class="error-container">
        <text>{{ errorMessage }}</text>
        <button class="retry-btn" @click="getBusinessData">
          重新加载
        </button>
      </view>

      <!-- 使用DetailCard组件展示详情信息 -->
      <template v-else-if="businessData">
        <!-- 项目基本信息 -->
        <DetailCard title="基本信息" :info-list="projectBasicInfo" />

        <!-- 项目财务信息 -->
        <DetailCard title="财务信息" :info-list="projectFinanceInfo" />

        <!-- 项目业务信息 -->
        <DetailCard title="业务信息" :info-list="projectBusinessInfo" />

        <!-- 流程信息 -->
        <DetailCard title="流程信息" :info-list="processInfo" />

        <!-- 文件列表 -->
        <AttachmentList
          v-if="projectFiles.length > 0"
          :attachments="projectFiles"
          preview-mode="list"
          :columns="3"
          :show-size="true"
          :show-download="true"
          @preview="handleFilePreview"
          @download="handleFileDownload"
        />

        <!-- 审批操作栏 -->
        <view class="approval-bar">
          <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
        </view>
      </template>
    </view>
  </view>
</template>

<style scoped>
.container {
  padding-bottom: 20px;
}

.content {
  padding: 20rpx;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.error-container {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.retry-btn {
  margin-top: 16px;
  padding: 8px 24px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}

/* 文件列表样式 */
.file-list-section {
  margin-top: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: #333;
}

.file-loading,
.file-error {
  margin-top: 20rpx;
  padding: 20rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.file-error {
  color: #ff4d4f;
}

/* 文件空状态样式 */
.file-empty {
  margin-top: 20rpx;
  padding: 60rpx 20rpx;
  text-align: center;
  background: #fff;
  border-radius: 12rpx;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 审批操作栏样式 */
.approval-bar {
  margin-top: 20rpx;
  padding-bottom: 20rpx;
}
</style>
